package com.lq.ecoldchain.ui.login

import android.arch.lifecycle.MutableLiveData
import android.view.View
import com.alibaba.android.arouter.launcher.ARouter
import com.lq.ecoldchain.base.BaseNavigator
import com.lq.ecoldchain.base.CommonLoadingState
import com.lq.ecoldchain.base.viewmodel.BaseViewModel
import com.lq.ecoldchain.config.AppConfig
import com.lq.ecoldchain.internet.BaseObserver
import com.lq.ecoldchain.util.MD5
import com.lq.ecoldchain.util.PrefsHelper
import com.lq.ecoldchain.util.toast
import com.tencent.mm.opensdk.constants.Build
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.WXAPIFactory

/*
*2018/12/22 0022  12:05
*function by lq
*/
class LoginViewModel(private val pref: PrefsHelper) : BaseViewModel() {
    val userName by lazy { MutableLiveData<String>() }
    val password by lazy { MutableLiveData<String>() }
    val loadingLayout by lazy { MutableLiveData<CommonLoadingState>() }
    val pwdCanSee by lazy { MutableLiveData<Boolean>() }
    val isSuccess by lazy { MutableLiveData<Boolean>() }

    init {
        userName.value = pref.username
        password.value = pref.password
        if (pref.autoLogin) login()
    }

    fun wxLogin(view: View) {
        val wxApi = WXAPIFactory.createWXAPI(view.context, AppConfig.WX_KEY_APP_ID)
        if (!wxApi.isWXAppInstalled) {
            toast { "请先安装微信客户端" }
        } else if (wxApi.wxAppSupportAPI < Build.PAY_SUPPORTED_SDK_INT) {
            toast { "请先更新微信客户端" }
        } else {
            val req = SendAuth.Req()
            req.scope = "snsapi_userinfo"
            req.state = "wechat_sdk_demo_test"
            wxApi.sendReq(req)
        }
    }


    fun login() {
        when (userName.value.isNullOrEmpty() || password.value.isNullOrEmpty()) {
            true -> toast { "请输入账号密码" }
            false -> BaseNetCore.ApiServiceImpl.login(userName.value!!, MD5.encode(password.value!!)).compose(RxTransformer.switchSchedulers()).subscribe(object : BaseObserver<String>() {
                override fun onSuccess(t: String?) {
                    pref.username = userName.value!!
                    pref.password = password.value!!
                    pref.token = t!!
                    pref.autoLogin = true
                    ARouter.getInstance().build(BaseNavigator.mainActivity).navigation()
                }

                override fun onFail(code: String) {}
            })
        }
    }


    private fun applyState(state: CommonLoadingState = CommonLoadingState.IDLE) {
        loadingLayout.value = state
        /* when(state){
             CommonLoadingState.ERROR->loadingLayout.value = CommonLoadingState.ERROR
             CommonLoadingState.EMPTY-> toast {"请输入账号密码"}
             CommonLoadingState.LOADING -> toast { "登录中" }
             else -> {
             }
         }*/
    }

}